﻿using Microsoft.AspNetCore.Http;
using RsCms.Core.Promote.Entities;
using RsCode;
using RsCode.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RsCms.Core.Promote
{
	public class PromoteDomainService:IPromoteDomainService
	{
        IRepository<PromoteInfo> promoteRepository;
        IRepository<PromoteCodeInfo> promoteCodeRepository;
        IHttpContextAccessor httpContextAccessor;
        public PromoteDomainService(IRepository<PromoteInfo> promoteRepository,
            IRepository<PromoteCodeInfo> promoteCodeRepository,
            IHttpContextAccessor httpContextAccessor)
        {
            this.promoteRepository = promoteRepository;
            this.promoteCodeRepository= promoteCodeRepository;
            this.httpContextAccessor= httpContextAccessor;
        }
		string LoginUserId
		{
			get
			{
				var claims = httpContextAccessor?.HttpContext?.User.Claims;
				return claims?.First(x => x.Type == "UserId").Value ?? "";
			}
		}

        //public async Task CreatePromoteInfoAsync(string promoteCode,)
        //{

        //}
		public async Task<PageData<PromoteInfo>> PagePromoteInfoAsync(int page,int pageSize)
        {
            string userId = LoginUserId;
            var promoteCodeInfo=await GetPromoteCodeAsync(userId);
            var select =promoteRepository.Select.Where(x => x.PromoteCode == promoteCodeInfo.Code).OrderByDescending(x=>x.Id);
            return await promoteRepository.PageAsync(page, pageSize, select);
        }

        public async Task<PromoteCodeInfo>GetPromoteCodeAsync(string userId)
        {
            return await promoteCodeRepository.Select.Where(x => x.UserId == userId).ToOneAsync();
        }
		public PromoteCodeInfo SavePromoteCodeAsync(PromoteCodeInfo info)
		{
			return promoteCodeRepository.InsertOrUpdate(info);
		}


	}
}
